﻿using System.Configuration;
using System.Web;
using System.Web.Configuration;
using Moq;
using NUnit.Framework;
using OpenWaves.ImageTransformations;
using OpenWaves.Web.ImageTransformations;

namespace OpenWaves.UnitTests.ImageTransformations
{
    [TestFixture]
    public class WebImageTransformationModuleImplementationTests
    {
        [Test]
        public void When_RequestRawUrl_inludes_valid_ImageTransofmrationInfo_ModuleImplementation_rewrites_path_to_point_to_transformed_image()
        {
            const string rawUrl = "/image.jpg?t=5363616C65546F4669743A35307831303031A7F818E1E08517A31FA953C94F256D418CA230060C6AEAA7FBD1C7A15B7238";

            var section = (MachineKeySection)ConfigurationManager.GetSection("system.web/machineKey");
            Assert.That(section.ValidationKey, 
                Is.EqualTo("B316E2A8F4F8E70E770884BAD826FF50605D0ED618640F3D79229C0D620B72BA967A426ECE3A10958E449A33E916E527F8C7D1A3E4C093CC4D8C6C2454A1E5C2"),
                "This test requires the same ValidationKey that was used to generate encoded image transofmration to be configured in app.config.");

            var responseMock = new Mock<HttpResponseBase>();
            responseMock.SetupGet(r => r.Cache).Returns(new Mock<HttpCachePolicyBase>().Object);

            var httpContextMock = new Mock<HttpContextBase>();
            httpContextMock.SetupGet(c => c.Request).Returns(CreateHttpRequestMock(rawUrl));
            httpContextMock.SetupGet(c => c.Response).Returns(responseMock.Object);
            httpContextMock.Setup(c => c.RewritePath("/transformed/image.jpg"));

            var imageTransformationServiceMock = new Mock<IWebImageTransformationService>();
            imageTransformationServiceMock
                .Setup(s => s.GetTransformedImageUrl(Url.Parse("/image.jpg"), It.IsAny<IImageTransformation>()))
                .Returns(Url.ParseRelative("/transformed/image.jpg"));

            var moduleImplementation = new WebImageTransformationModuleImplementation(imageTransformationServiceMock.Object);

            moduleImplementation.PostAuthorizeRequest(httpContextMock.Object);
        }

        private static HttpRequestBase CreateHttpRequestMock(string rawUrl)
        {
            var httpRequestMock = new Mock<HttpRequestBase>();
            httpRequestMock.SetupGet(r => r.RawUrl).Returns(rawUrl);
            return httpRequestMock.Object;
        }
    }
}